package cn.jbolt.user.auth.api;

import cn.jbolt.core.api.*;
import cn.jbolt.core.api.httpmethod.JBoltHttpGet;
import cn.jbolt.core.api.httpmethod.JBoltHttpPost;
import cn.jbolt.core.cache.JBoltGlobalConfigCache;
import cn.jbolt.core.cache.JBoltUserCache;
import cn.jbolt.core.captcha.JBoltCaptcha;
import cn.jbolt.core.common.enums.JBoltLoginState;
import cn.jbolt.core.crossorigin.CrossOrigin;
import cn.jbolt.core.model.LoginLog;
import cn.jbolt.core.model.OnlineUser;
import cn.jbolt.core.model.User;
import cn.jbolt.core.service.JBoltLoginLogUtil;
import cn.jbolt.core.service.JBoltOnlineUserService;
import cn.jbolt.core.service.JBoltUserService;
import com.jfinal.aop.Inject;
import com.jfinal.core.Path;
import com.jfinal.core.paragetter.Para;
import com.jfinal.kit.Ret;


/**
 * 非微信服务号 小程序环境使用
 * 使用jb_user登录信息 登录拿到jwt授权 使用系统用户登录APP H5页面等场景
 */
@CrossOrigin
@Path("/api/user/auth")
public class JBoltUserAuthApiController extends JBoltApiBaseController {
    @Inject
    JBoltUserService service;
    @Inject
    JBoltOnlineUserService onlineUserService;
    /**
     * 执行模拟登录授权
     * 正式环境需要去掉
     */
    @JBoltApplyJWT(604800000L)//默认一周
    @JBoltHttpGet
    public void testLogin() {
        Long userId = getLong(0);
        User user = isOk(userId)?JBoltUserCache.me.get(userId):service.getOneSystemAdmin();
        if(user == null){
            renderJBoltApiFail("无有效管理用户");
            return;
        }
        //创建登录日志
        LoginLog log= JBoltLoginLogUtil.createLoginLog(getRequest());
        log.setUsername(user.getUsername());
        log.setLoginState(JBoltLoginState.LOGIN_SUCCESS.getValue());
        log.save();
        //处理用户登录信息 异地登录异常信息
        boolean isRemoteLogin=service.processUserRemoteLogin(user,log);
        service.processUserLoginInfo(user,isRemoteLogin,log);
        OnlineUser onlineUser = onlineUserService.processUserLogin(user,log);
        if(onlineUser == null){
            renderJBoltApiFail("在线用户生成异常 无法成功授权");
            return;
        }
        //设置当前登录有用户
        JBoltApiKit.setApplyJwtUser(new JBoltApiUserBean(JBoltApiKit.getApplicationId(),user.getId(), user.getUsername(),true,onlineUser.getId()));
        //告知客户端登录成功
        renderNull();
    }

    /**
     * 执行登录授权
     * @param userName 账号
     * @param password 密码
     */
    @JBoltApplyJWT
    @JBoltHttpPost
    public void index(@Para("userName")String userName,@Para("password")String password) {
        if(hasNotOk(userName,password)){
            renderJBoltApiFail("用户名或密码错误");
            return;
        }
        if(password.length()>128){
            renderJBoltApiFail("密码长度不能超过128位");
            return;
        }
        //创建登录日志
        LoginLog log= JBoltLoginLogUtil.createLoginLog(getRequest());
        log.setUsername(userName);
        //根据全局配置判断是否需要验证码 默认需要
        boolean checkCaptcha= JBoltGlobalConfigCache.me.isJBoltLoginUseCapture();
        if(checkCaptcha){
            boolean checkSuccess=validateCaptcha(JBoltCaptcha.DEFAULT_PARAM_NAME);
            if(!checkSuccess) {
                log.setLoginState(JBoltLoginState.CAPTURE_ERROR.getValue());
                log.save();
                renderJsonFail(JBoltLoginState.CAPTURE_ERROR.getText());
                return;
            }
        }


        //执行查询用户
        Ret ret = service.getUser(userName,password);
        if(ret.isFail()){
            log.setLoginState(JBoltLoginState.USERNAME_PWD_ERROR.getValue());
            log.save();
            renderJBoltApiRet(ret);
            return;
        }
        //用户存在 判断状态
        User user = ret.getAs(DATA_RANGE_PARAM_NAME);
        if(user == null){
            log.setLoginState(JBoltLoginState.USERNAME_PWD_ERROR.getValue());
            log.save();
            renderJBoltApiFail("用户["+userName+"]信息不存在");
            return;
        }
        log.setUserId(user.getId());
        //判断状态
        if(!user.getEnable()){
            log.setLoginState(JBoltLoginState.ENABLE_ERROR.getValue());
            log.save();
            renderJBoltApiFail("用户["+userName+"]已被禁用");
            return;
        }
        //检测角色权限分配
        if(notOk(user.getRoles())&&(user.getIsSystemAdmin()==null|| !user.getIsSystemAdmin())){
            log.setLoginState(JBoltLoginState.NOT_ASSIGN_ROLE_ERROR.getValue());
            log.save();
            renderJBoltApiFail(JBoltLoginState.NOT_ASSIGN_ROLE_ERROR.getText());
            return;
        }
        log.setLoginState(JBoltLoginState.LOGIN_SUCCESS.getValue());
        log.save();
        //处理用户登录信息 异地登录异常信息
        boolean isRemoteLogin=service.processUserRemoteLogin(user,log);
        service.processUserLoginInfo(user,isRemoteLogin,log);
        //onlineUser添加
        OnlineUser onlineUser = onlineUserService.processUserLogin(user,log);
        if(onlineUser == null){
            renderJBoltApiFail("在线用户生成异常 无法成功授权");
            return;
        }
        //设置当前登录有用户
        JBoltApiKit.setApplyJwtUser(new JBoltApiUserBean(JBoltApiKit.getApplicationId(),user.getId(), user.getUsername(),true,onlineUser.getId()));
        //告知客户端登录成功
        renderJBoltApiSuccess();
    }
}
